package com.myz.app.shiro.realms;


import com.myz.app.entity.Permission;
import com.myz.app.entity.Role;
import com.myz.app.entity.User;
import com.myz.app.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * principal 主要的
 * 授权
 * Created by maoyz on 17-10-9.
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    private IUserService userService;

    //　验证用户名和密码
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1 仅支持UsernamePasswordToken类型的Token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 2 取出username
        String username =  token.getUsername();

        User user = null;

        // 3 调用数据库，从中取出username对应信息
        // user = userService.getPasswordByName(username);

        if (null != user){
            // 若存在，将此用户存放到登录认证info中
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(),getName());
            // 存放session中
            setSession("currentUser",user);
            return info;
        }

        return null;
    }

    private void setSession(Object key, Object val) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser){
            Session session = currentUser.getSession();
            if(null != session){
                session.setAttribute(key,val);
            }
        }
    }

    // 授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String currentUsername = (String) super.getAvailablePrincipal(principalCollection);

        // 1 从PrincipalCollection获取用户登录信息
        Object principal = principalCollection.getPrimaryPrincipal();

        // 2 利用登录用户的信息查询用户的角色或权限
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();

        if (null == currentUsername){
            return null;
        }

        List<User> users = userService.getUserByName(currentUsername);

        for (User user : users) {
            if (null != user){
                List<Role> rolesList = user.getRoles();
                for (Role role : rolesList) {
                    if (null != role){
                        roles.add(role.getRoleType());
                        List<Permission> permissionList = role.getPermissions();
                        for (Permission permission : permissionList) {
                            if (null != permission){
                                permissions.add(permission.getPermissionType());
                            }
                        }
                    }
                }
            }
        }

        //　3 创建SimpleAuthorizationInfo,设置role属性
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加角色信息
        info.addRoles(roles);
        //　添加权限信息
        info.addStringPermissions(permissions);
        // 4　返回SimpleAuthorizationInfo
        return info;
    }
}
